"use strict";
const Sequelize = require('sequelize');
let core, config, logger, loggerQuery, sequelize, models = {},
  _ = require('lodash');

let serviceName = 'mysql';
let mysql = {
  assert: (error, sql) => {
    if (error) {
      if (sql) {
        logger.error('Error sql: [' + sql + ']');
      }
      logger.error(error);
      throw '[' + serviceName + '] ' + error;
    }
  },
  init: (name, c) => new Promise((callback) => {
    serviceName = name;
    core = c;
    logger = core.getLogger(serviceName);
    loggerQuery = core.getLogger(serviceName + '-query');
    config = core.getConfig(serviceName);
    let options = {
      logging: (sql, time) => config.log_query && loggerQuery.info(`${sql} - time: ${time} ms`),
      benchmark: config.log_query,
      dialect: serviceName,
      pool: config.pool,
      replication: {},
    };
    if (!config.master) {
      throw 'MASTER config not found.';
    }
    options.replication.write = {
      host: config.master.host,
      port: config.master.port,
      username: config.master.username,
      password: config.master.password,
      database: config.master.database,
    };
    if (config.slave && _.isArray(config.slave) && config.slave.length) {
      options.replication.read = [];
      _.forEach(config.slave, (slave) => {
        options.replication.read.push({
          host: slave.host || config.master.host,
          port: slave.port || config.master.port,
          username: slave.username || config.master.username,
          password: slave.password || config.master.password,
          database: slave.database || config.master.database,
        })
      });
    } else {
      options.replication.read = [{
        host: config.master.host,
        port: config.master.port,
        username: config.master.username,
        password: config.master.password,
        database: config.master.database,
      }]
    }
    sequelize = new Sequelize(options);
    // 定义 model
    models = require('./models')(sequelize, Sequelize, logger);
    core.getModel = (model) => _.get(models, model, false);

    sequelize.authenticate().then(() => {
      callback();
    }).catch(err => {
      throw 'Unable to connect to the database:', err;
    });
  }),
  uninit: () => {
    if (sequelize) {
      // sequelize.close();
    }
  },
  getModel: (model) => _.get(models, model, false),
};

module.exports = mysql;
